#import "StringResponder.h"
#import <stdio.h>
#import <stdlib.h>
#import <string.h>

@implementation StringResponder
  
+ new
{
  self = [super new];
  list = (listElt *)malloc(sizeof(listElt));  // to simplify searching, list head never has valid data
  list->next = NULL;
  maxlen = 0;
  return self;
}

- free
{
  listElt *p, *q;

  p=list->next;
  while (p) {
    q=p->next;
    free(p->s);
    free(p);
    p=q;
  }
  free(list);
  return [super free];
}

- addString:(char *)string returnValue:(int)tag
{
  listElt *p;
  int len;

  len = strlen(string);
  if (len>maxlen) maxlen=len;
  for (p=list; p->next; p=p->next)
    ;
  p->next = (listElt *)malloc(sizeof(listElt));
  p = p->next;
  p->next = NULL;
  p->s = (char *)malloc(len+1);
  strcpy(p->s, string);
  p->strlen = len;
  if (tag==0) {
    fprintf(stderr,"StringResponder:registered tag must be non-zero, will make it -1\n");
    tag=(-1);
  }
  p->tag = tag;
  p->matchedChars = 0;
  return self;
}

- (int) inputString:(char *)input
{
  int i,len;
  BOOL seen;

  len=strlen(input);
  seen = NO;
  for (i=0; i<len && !seen; i++)
    seen = [self inputChar:input[i]];
  return seen;
}

- (int) inputChar:(char)ichar
{
  listElt *p;
  int m;

  for (p=list->next; p; p=p->next) {
    m = p->matchedChars;
    if ((p->s)[m] == ichar) {
      (p->matchedChars)++;
      if (p->strlen == m+1) {  // trigger is pulled
	p->matchedChars = 0;
	return p->tag;
      }
    }
    else
      p->matchedChars = 0;
  }
  return 0;
}

@end
